`

Filtering with grep

The grep command is one of the most popular Linux commands out there

today. We use grep to filter out information of interest from streams. At its most

basic form, you can use it like so (Listing 2-19).

$ grep "35.237.4.214" log.txt

Listing 2-19

Filtering for a specific string from a file

This grep command will read the file and extract any lines containing the IP

address 35.237.4.214 from it.

We can even grep for multiple patterns simultaneously. The following

backslash pipe (\|) acts as an or condition (Listing 2-20).

$ grep "35.237.4.214\|13.66.139.0" log.txt

Listing 2-20

Filtering for two specific strings

Alternatively, you could use multiple grep patterns with the -e argument to

accomplish the same thing (Listing 2-21).

$ grep -e "35.237.4.214" -e "13.66.139.0" log.txt

Listing 2-21

Filtering for two specific strings with grep -e

As you learned in Chapter 1, we can use the pipe (|) command to provide one

commands output as the input to another. In the following example, we run the

ps command and use grep to filter out a specific line. The ps command lists the

processes on the system:

$ ps | grep TTY

By default, grep is case sensitive. We can make our search case insensitive

using the -i flag (Listing 2-22).

$ ps | grep -i tty

Listing 2-22

A case-insensitive search with grep

We can also use grep to exclude lines containing a certain pattern using the

-v argument, like in Listing 2-23.

$ grep -v "35.237.4.214" log.txt

Listing 2-23

Excluding lines containing a string

To print only the matched pattern, and not the entire line at which the matched

pattern was found, use -o (Listing 2-24).

$ grep -o "35.237.4.214" log.txt

Listing 2-24

Printing only the matching pattern

Black Hat Bash (Early Access) © 2023 by Dolev Farhi and Nick Aleks